package com.malamute.core.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.malamute.core.constant.SystemConstant;

/**
 * @author Aceguan
 * @description TODO
 * @date 2012-2-20 下午11:34:14
 * @version v1.0
 */
public class UserLoginFilter extends HttpServlet implements Filter {
	private Logger log = Logger.getLogger(UserLoginFilter.class);

	private FilterConfig filterConfig;

	/*
	 * (non-Javadoc)
	 * 
	 * @param filterConfig
	 * 
	 * @throws ServletException
	 * 
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @param request
	 * 
	 * @param response
	 * 
	 * @param chain
	 * 
	 * @throws IOException
	 * 
	 * @throws ServletException
	 * 
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// LGOIN FILTER
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse rep = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		if (session.getAttribute(SystemConstant.SES_USER_LOGIN) == null) {
			// 跳转登录页面
			String noLogin = filterConfig.getInitParameter("noLogin");
			// System.out.println(req.getServerPort()+"req.getContextPath()");
			// rep.sendRedirect(req.getContextPath() + noLogin);
			// ACE:以下内容注释暂时先不拦截
			if (log.isDebugEnabled()) {
				chain.doFilter(request, response);
			} else {
				RequestDispatcher dispatcher = request
						.getRequestDispatcher(noLogin);
				dispatcher.forward(request, response);
			}

		} else {
			chain.doFilter(request, response);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
